// 类型断言、类型收敛( is ， in， typeof ， instanceof操作符)
/*

person 可能是 User，也可能是 Admin，
而TS没有足够的信息确实是哪一种

解决方案的思路就是告诉TS【person当前是User还是Admin】

1. 将person断言为准确的类型
  (<Admin>person).role (<User>person.occupation)

2. 使用类型收缩，比如is/in/typeof/instanceof等，使得TS能够获取到当前类型
  if("role" in person) => TS自动推导为Admin

*/
interface User {
  name: string;
  age: number;
  occupation: string;
}

interface Admin {
  name: string;
  age: number;
  role: string;
}

export type Person = User | Admin;

export const persons: Person[] = [
  {
      name: 'Max Mustermann',
      age: 25,
      occupation: 'Chimney sweep'
  },
  {
      name: 'Jane Doe',
      age: 32,
      role: 'Administrator'
  },
  {
      name: 'Kate Müller',
      age: 23,
      occupation: 'Astronaut'
  },
  {
      name: 'Bruce Willis',
      age: 64,
      role: 'World saver'
  }
];

/*
export function logPerson(person: Person) {
  let additionalInformation: string;
  if ((person as Admin).role) {
      additionalInformation = (person as Admin).role;
  } else {
      additionalInformation = (person as User).occupation;
  }
  console.log(` - ${person.name}, ${person.age}, ${additionalInformation}`);
}
*/
export function logPerson(person: Person) {
  let additionalInformation: string;
  if ('role' in person) {
      additionalInformation = person.role;
  } else {
      additionalInformation = person.occupation;
  }
  console.log(` - ${person.name}, ${person.age}, ${additionalInformation}`);
}

persons.forEach(logPerson);